package com.hoperun.checkcloth.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;

import com.blankj.utilcode.util.ResourceUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hoperun.checkcloth.R;
import com.hoperun.checkcloth.adapter.SJZDAdapter;
import com.hoperun.checkcloth.adapter.XcslAdapter;
import com.hoperun.checkcloth.base.MIP_BaseActivity;
import com.hoperun.checkcloth.entity.ClothEntity;
import com.hoperun.checkcloth.entity.SJZDEntity;
import com.hoperun.checkcloth.entity.XCXX;
import com.hoperun.checkcloth.fragment.CountDialogFragment;
import com.hoperun.checkcloth.net.IServiceImpl;
import com.hoperun.checkcloth.net.RequestServiceImpl;
import com.hoperun.checkcloth.util.SharedPreUtil;
import com.hoperun.checkcloth.view.SimpleDialog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class PibuMainActivity extends MIP_BaseActivity implements OnClickListener {

    /**
     * 查询词典类型的数据字典id
     **/
    private static final String SJZDID_TASKLX = "BADLX";

    private EditText monadNoEt;

    private EditText pishuEt;
    private EditText clothNoEt;
    private EditText batchNoEt;
    // private EditText machineNoEt;
    private EditText weightEt;
    private EditText meterLongEt;
    private EditText gradeEt;
    private EditText clothWorkerEt;

    private ListView listView;

    private GridView xclxGridview;
    // private GridView bzGridview;
    private Button xclxBtn;
    private Button bzBtn;

    private Button okBtn;
    private Button backBtn;
    /**
     * 瑕疵类型适配器
     **/
    private SJZDAdapter xclxAdapter;

    /** 备注适配器 **/
    // private SJZDAdapter bzAdapter;
    /**
     * 所有瑕疵类型
     **/
    private List<SJZDEntity> mALLXclxList = new ArrayList<SJZDEntity>();
    /**
     * 备注
     **/
    private List<SJZDEntity> mbzList = new ArrayList<SJZDEntity>();

    /**
     * 实际需要显示的数据
     **/
    private List<SJZDEntity> mList = new ArrayList<SJZDEntity>();

    /**
     * 瑕疵数量适配器
     **/
    private XcslAdapter xcslAdapter;
    /**
     * 瑕疵信息集合
     **/
    private List<XCXX> mXcxxs = new ArrayList<XCXX>();

    private CountDialogFragment mDialog;

    ClothEntity mCloth = new ClothEntity();

    /**
     * 三联单号是否正确
     **/
    private boolean isMonadNoCorrect = false;

    /**
     * 匹数
     **/
    private int mPsSum = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pibu_activity_main);
        initViews();
        initEvents();
        querySJZD(SJZDID_TASKLX);
    }

    private void initViews() {

        monadNoEt = (EditText) findViewById(R.id.monadNoEt);
        pishuEt = (EditText) findViewById(R.id.pishuEt);
        clothNoEt = (EditText) findViewById(R.id.clothNoEt);
        batchNoEt = (EditText) findViewById(R.id.batchNoEt);
        weightEt = (EditText) findViewById(R.id.weightEt);
        meterLongEt = (EditText) findViewById(R.id.meterLongEt);
        gradeEt = (EditText) findViewById(R.id.gradeEt);
        clothWorkerEt = (EditText) findViewById(R.id.clothWorkerEt);
        listView = (ListView) findViewById(R.id.xcListView);

        xclxBtn = (Button) findViewById(R.id.xclxBtn);
        bzBtn = (Button) findViewById(R.id.bzBtn);
        okBtn = (Button) findViewById(R.id.okBtn);
        backBtn = (Button) findViewById(R.id.backBtn);


        xclxGridview = (GridView) findViewById(R.id.xclxGridView);
        // 计算布局实际高度
        ViewTreeObserver vto = xclxGridview.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                xclxGridview.getViewTreeObserver()
                        .removeGlobalOnLayoutListener(this);
                int height = xclxGridview.getHeight();
                int itemHeight = (height) / totalRows;// 得到实际每行显示的高度
                xclxAdapter.setItemHeight(itemHeight);// 设置 行高
                xclxAdapter.notifyDataSetChanged();
            }
        });
        xclxAdapter = new SJZDAdapter(this, mList);
        xclxGridview.setAdapter(xclxAdapter);

        xcslAdapter = new XcslAdapter(this, mXcxxs);
        listView.setAdapter(xcslAdapter);

        String empID = (String) SharedPreUtil.getValue(this,
                SharedPreUtil.YHBH, "");
        String clothWorker = (String) SharedPreUtil.getValue(this,
                SharedPreUtil.YHMC, "");
        mCloth.EMPID = empID;
        mCloth.CLOTHWORKER = clothWorker;
        if (!TextUtils.isEmpty(clothWorker)) {
            clothWorkerEt.setText(clothWorker);
        }
        try {
            mPsSum = Integer.parseInt((String) SharedPreUtil.getValue(this,
                    SharedPreUtil.DATASUM, ""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        pishuEt.setText(String.valueOf(mPsSum));
    }

    private void initEvents() {

        xclxBtn.setOnClickListener(this);
        bzBtn.setOnClickListener(this);
        okBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);

        monadNoEt.setOnKeyListener((v, keyCode, event) -> {
            if (event != null
                    && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
                    && event.getAction() == KeyEvent.ACTION_UP) {

                String monadNo = monadNoEt.getText().toString().trim();
                if (monadNo.length() >= 4) {
                    // 查询信息
                    queryByMonadNo(monadNo);
                } else {
                    SimpleDialog
                            .show(PibuMainActivity.this, getResources().getString(R.string.monadno_not_right));
                }
                return true;
            }
            return false;
        });

        xclxAdapter.setOnBtnClickListener(position -> {
            SJZDEntity entity = mList.get(position);
            if (entity != null) {
                for (int i = 0; i < mXcxxs.size(); i++) {
                    XCXX xcxx = mXcxxs.get(i);
                    if (xcxx.XCID.equals(entity.KEYCODE)) {
                        mXcxxs.get(i).XCSL++;
                        xcslAdapter.notifyDataSetChanged();
                        return;
                    }
                }
                // 添加一条记录到疵点信息列表中,默认数量为1
                mXcxxs.add(0, new XCXX(entity.KEYCODE, entity.SJXZ, 1));
                xcslAdapter.notifyDataSetChanged();
            }
        });
        xcslAdapter.setOnDeleteClickListener(position -> {
            // 删除一条记录
            mXcxxs.remove(position);
            xcslAdapter.notifyDataSetChanged();
        });

        xcslAdapter.setOnCounterClickListener(position -> {

            int result = mXcxxs.get(position).XCSL;
            mDialog = CountDialogFragment.newInstance(result);
            mDialog.show(getSupportFragmentManager(), "CountDialog");
            mDialog.setOnOKClickListener(result1 -> {
                mXcxxs.get(position).XCSL = result1;
                xcslAdapter.notifyDataSetChanged();
                mDialog.dismiss();
            });
        });
        monadNoEt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                isMonadNoCorrect = false;// 三联号改变了需要重新校验

                mCloth.CLOTHNO = "";
                mCloth.BATCHNO = "";
                mCloth.MACHINENO = "";
                mCloth.WEIGHT = "";
                mCloth.METERLONG = "";
                mCloth.GRADENO = "";

                clothNoEt.setText(mCloth.CLOTHNO);
                batchNoEt.setText(mCloth.BATCHNO);
                weightEt.setText(mCloth.WEIGHT);
                meterLongEt.setText(mCloth.METERLONG);
                gradeEt.setText(mCloth.GRADENO);

                mXcxxs.clear();

                xcslAdapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.xclxBtn:
                mList.clear();
                mList.addAll(mALLXclxList);
                xclxAdapter.notifyDataSetChanged();
                xclxBtn.setBackground(ResourceUtils.getDrawable(R.drawable.btn_blue_light));
                xclxBtn.setTextColor(this.getResources().getColor(R.color.white));
                bzBtn.setBackground(ResourceUtils.getDrawable(R.drawable.btn_gray));
                bzBtn.setTextColor(this.getResources().getColor(R.color.black));
                break;
            case R.id.bzBtn:

                mList.clear();
                mList.addAll(mbzList);
                xclxAdapter.notifyDataSetChanged();
                xclxBtn.setBackground(ResourceUtils.getDrawable(R.drawable.btn_gray));
                xclxBtn.setTextColor(this.getResources().getColor(R.color.black));
                bzBtn.setBackground(ResourceUtils.getDrawable(R.drawable.btn_blue_light));
                bzBtn.setTextColor(this.getResources().getColor(R.color.white));
                break;
            case R.id.okBtn:
                String monadNo = monadNoEt.getText().toString().trim();
                if (TextUtils.isEmpty(monadNo)) {
                    SimpleDialog.show(this, getResources().getString(R.string.please_scan_monadno));
                    return;
                } else if (!isMonadNoCorrect) {
                    SimpleDialog.show(this, getResources().getString(R.string.monadno_checked_fail_and_tray_again));
                    return;
                }
                mCloth.MONADNO = monadNo;
                commit(mCloth, mXcxxs);
                break;
            case R.id.backBtn:
                this.finish();
                break;
            default:
                break;
        }

    }

    // 总行数
    private static int totalRows = 9;
    private static int columns = 4;
    private static int rows = 4;
    private static int totalnums = columns * rows;

    // 添加空数据，以填补空白，满足行数要求
    private List<SJZDEntity> addEmptyList(List<SJZDEntity> list) {

        int emptySize = totalnums - list.size();
        for (int i = 0; i < emptySize; i++) {
            list.add(new SJZDEntity());
        }
        return list;

    }

    /**
     * 4.4. 查询数据字典
     *
     * @param SJZDID
     */
    private void querySJZD(String SJZDID) {
        showWait();
        RequestServiceImpl.querySJZD(mMIPHandler,
                IServiceImpl.TYPE_querySJZDBySJZDID, SJZDID);
    }

    /**
     * 根据三联号获取相关基本信息
     *
     * @param monadNo
     */
    private void queryByMonadNo(String monadNo) {
        showWait();
        String YHBH = (String) SharedPreUtil.getValue(this, SharedPreUtil.YHBH,
                "");
        RequestServiceImpl.queryByMonadNo(mMIPHandler,
                IServiceImpl.TYPE_zjQueryByMonadNo, monadNo, YHBH);
    }

    /**
     * 提交瑕疵接口
     *
     * @param cloth
     * @param XCXXs
     */
    private void commit(ClothEntity cloth, List<XCXX> XCXXs) {
        showWait();
        RequestServiceImpl.checkCommit(mMIPHandler,
                IServiceImpl.TYPE_zjClothQtyCheckDetailCommit, cloth, XCXXs);
    }

    @Override
    public void onPostHandle(int requestType, Object objBody, boolean error)
            throws Exception {
        stopWait();
        String msg = "";
        String opt = "";
        if (error) {
            switch (requestType) {
                case IServiceImpl.TYPE_querySJZDBySJZDID:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("ERRORMESSAGE");
                        opt = jsonObj.optString("FLAG");
                        if ("SUCCESS".equals(opt)) {
                            JSONArray jsonArray1 = jsonObj.optJSONArray("DATA");
                            JSONArray jsonArray2 = jsonObj.optJSONArray("DATA2");
                            JSONArray jsonArray3 = jsonObj.optJSONArray("DATA3");
                            JSONArray jsonArray4 = jsonObj.optJSONArray("DATA4");
                            if (jsonArray1 != null && jsonArray2 != null
                                    && jsonArray3 != null && jsonArray4 != null) {

                                Gson gson = new Gson();
                                List<SJZDEntity> xclxs1 = gson.fromJson(
                                        jsonArray1.toString(),
                                        new TypeToken<List<SJZDEntity>>() {
                                        }.getType());
                                List<SJZDEntity> xclxs2 = gson.fromJson(
                                        jsonArray2.toString(),
                                        new TypeToken<List<SJZDEntity>>() {
                                        }.getType());
                                List<SJZDEntity> xclxs3 = gson.fromJson(
                                        jsonArray3.toString(),
                                        new TypeToken<List<SJZDEntity>>() {
                                        }.getType());
                                List<SJZDEntity> xclxs4 = gson.fromJson(
                                        jsonArray4.toString(),
                                        new TypeToken<List<SJZDEntity>>() {
                                        }.getType());
                                addEmptyList(xclxs1);
                                mALLXclxList.addAll(xclxs1);
                                mALLXclxList.addAll(xclxs2);
                                mALLXclxList.addAll(xclxs3);
                                mbzList.addAll(xclxs4);
                                mList.addAll(mALLXclxList);
                                xclxAdapter.notifyDataSetChanged();

                            } else {
                                SimpleDialog.show(this, getResources().getString(R.string.query_sjzd_fail));
                            }

                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                SimpleDialog.show(this, getResources().getString(R.string.query_sjzd_fail));
                            } else {
                                SimpleDialog.show(this, msg);
                            }

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, getResources().getString(R.string.query_sjzd_fail));
                    }
                    break;

                case IServiceImpl.TYPE_zjQueryByMonadNo:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("ERRORMESSAGE");
                        opt = jsonObj.optString("FLAG");


                        if ("SUCCESS".equals(opt)) {
                            JSONObject data = jsonObj.optJSONObject("DATA");
                            //2019-6-23新增弹出提示
                            String levelFlag = jsonObj.optString("LEVELFLAG");
                            if (!TextUtils.isEmpty(levelFlag)) {
                                SimpleDialog.show(this, levelFlag);
                            }

                            if (data != null) {
                                isMonadNoCorrect = true;// 查询成功
                                Gson gson = new Gson();

                                mCloth = gson.fromJson(data.toString(),
                                        ClothEntity.class);
                                mCloth.EMPID = (String) SharedPreUtil.getValue(
                                        this, SharedPreUtil.YHBH, "");
                                mCloth.CLOTHWORKER = (String) SharedPreUtil
                                        .getValue(this, SharedPreUtil.YHMC, "");

                                clothNoEt.setText(mCloth.BH_ZZ);
                                batchNoEt.setText(mCloth.BATCHNO);
                                weightEt.setText(mCloth.WEIGHT);
                                meterLongEt.setText(mCloth.METERLONG);
                                gradeEt.setText(mCloth.GRADENO);
                            }

                            JSONArray jsonArray = jsonObj.optJSONArray("DATALIST");
                            if (jsonArray != null) {
                                Gson gson = new Gson();
                                mXcxxs.clear();
                                List<XCXX> xcxxs = gson.fromJson(
                                        jsonArray.toString(),
                                        new TypeToken<List<XCXX>>() {
                                        }.getType());
                                mXcxxs.addAll(xcxxs);
                                xcslAdapter.notifyDataSetChanged();
                            }

                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                SimpleDialog.show(this, getResources().getString(R.string.query_fail));
                            } else {
                                SimpleDialog.show(this, msg);
                            }

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, getResources().getString(R.string.query_fail));
                    }
                    break;
                case IServiceImpl.TYPE_zjClothQtyCheckDetailCommit:
                    try {
                        JSONObject jsonObj = new JSONObject((String) objBody);
                        msg = jsonObj.optString("ERRORMESSAGE");
                        opt = jsonObj.optString("FLAG");
                        if ("SUCCESS".equals(opt)) {
                            SimpleDialog.show(this, getResources().getString(R.string.insert_success));

                            monadNoEt.setText("");

                            mCloth.CLOTHNO = "";
                            mCloth.BATCHNO = "";
                            mCloth.MACHINENO = "";
                            mCloth.WEIGHT = "";
                            mCloth.METERLONG = "";
                            mCloth.GRADENO = "";

                            clothNoEt.setText(mCloth.CLOTHNO);
                            batchNoEt.setText(mCloth.BATCHNO);
                            weightEt.setText(mCloth.WEIGHT);
                            meterLongEt.setText(mCloth.METERLONG);
                            gradeEt.setText(mCloth.GRADENO);

                            // 清空瑕疵信息列表
                            mXcxxs.clear();
                            xcslAdapter.notifyDataSetChanged();

                            mPsSum++;
                            pishuEt.setText(String.valueOf(mPsSum));
                            SharedPreUtil.putValue(this, SharedPreUtil.DATASUM, mPsSum+"");
                        } else {
                            if (TextUtils.isEmpty(msg)) {
                                SimpleDialog.show(this, getResources().getString(R.string.insert_fail));
                            } else {
                                SimpleDialog.show(this, msg);
                            }

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        SimpleDialog.show(this, getResources().getString(R.string.insert_fail));
                    }
                    break;

            }
        } else {
            if (objBody != null) {
                String obj = objBody.toString();
                SimpleDialog.show(this, obj);
            }

        }

    }

}
